import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { PageLoading, SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from 'umi';
import { history, Link, useModel } from 'umi';
import type { RequestConfig } from 'umi';
import defaultSettings from '../config/defaultSettings';
import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
import { getMenuList } from './services/mockApi';
import fixMenuItemIcon from './utils/fixMenuItemIcon';
import { mergeRoutes } from './utils/roles';
import { authHeaderInterceptor } from './utils/request';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
const systemTitle = '腾跃科技';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings,
  };
}

let extraRoutes: any[] | undefined = undefined;
let menuTree: any[] = [];
let menuList: any[] = [];
export async function patchRoutes({ routes }) {
  if (extraRoutes) {
    const list = mergeRoutes(extraRoutes);
    routes.forEach((route: any) => {
      if (route.path == '/') {
        menuTree = [];
        menuTree.push(...route.routes);
        menuTree.push(...list);
        //使用push，会找不到模块不知是否bug
        route.routes.unshift(...list);
      }
    });
  }
  console.log('路由信息:', routes);
}

export async function render(oldRender) {
  await loadMenu();
  oldRender();
}
async function loadMenu() {
  const res = await getMenuList();
  menuList = res.data.map((item: any) => {
    const obj = {
      ...item,
      hideInMenu: item.hideInMenu == '1' ? true : false,
    };
    Object.keys(obj).forEach((key) => {
      if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
        delete obj[key];
      } else if (obj[key] === 'true') {
        obj[key] = true;
      } else if (obj[key] === 'false') {
        obj[key] = false;
      }
    });
    return obj;
  });
  extraRoutes = initMenu(
    menuList.filter((item) => item.path),
    0,
  );
}
function initMenu(menus: [], parent: number) {
  const list = menus.filter((item) => item.parent == parent);
  list.forEach((item) => {
    //if (item.type === 1) {
    item.routes = initMenu(menus, item.id);
    //}
  });
  return list;
}
export function onRouteChange({ matchedRoutes, location }) {
  if (matchedRoutes.length) {
    const route = matchedRoutes[matchedRoutes.length - 1].route;
    if (route.path == '/module/:moduleId') {
      const menu = menuList.find((item: any) => item.path == location.pathname);
      if (menu) {
        setTimeout(() => {
          document.title = menu.name + ' - ' + systemTitle;
        }, 100);
      }
    }
  }
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    locale: false,
    title: systemTitle,
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    /* waterMarkProps: {
      content: initialState?.currentUser?.name,
    }, */
    //footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;

      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push({ pathname: loginPath });
      }
    },
    menu: {
      locale: false,
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      params: {
        userId: initialState?.currentUser?.userid,
      },
      request: async (params, defaultMenuData) => {
        // initialState.currentUser 中包含了所有用户信息
        //console.log(333, extraRoutes);
        //defaultMenuData.push(...extraRoutes);
        return fixMenuItemIcon(menuTree);
      },
    },
    links: isDev
      ? [
          <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
          <Link to="/~docs" key="docs">
            <BookOutlined />
            <span>业务组件文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

export const request: RequestConfig = {
  // 新增自动添加AccessToken的请求前拦截器
  requestInterceptors: [authHeaderInterceptor],
};
